<?php
    include_once $_SERVER['DOCUMENT_ROOT']."/controller/connect.php";
    include_once $_SERVER['DOCUMENT_ROOT']."/controller/weixinUtil.php";

    $tool = new weixinTool("HPQwjnca_An3LjptuP8zdQWvxkOANDn3FhLygAHLwe0");
    $token = $tool->access_token;
    $userId = -1;

    //    得到URI中的code值
    function getCode(){
        $pos1 = strpos($_SERVER['REQUEST_URI'], "code=");
        $pos2 = strpos($_SERVER['REQUEST_URI'], "&state");
        if($pos1 != null && $pos2 != null && $pos2-$pos1 > 0){
            $temp = substr($_SERVER['REQUEST_URI'], $pos1+5, $pos2-$pos1-5);
        }
        return $temp;
    }
    $code = getCode();
    //    获取微信企业号的用户UserId
    $userInfo = $tool->get_user_info_by_code($code);
    $weixinId = $userInfo['UserId'];

    //根据weixinId在数据库中查询userId
    $sql = "select * from user where weixinId = '{$weixinId}'";
    $conn = new db();
    $db = $conn->getDBConn();
    $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存

    if($row){
        $userId = $row['userId'];
    }

?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- meta使用viewport以确保页面可自由缩放 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 引入 bootstrap 样式 -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!--    <link rel="stylesheet" href="css/clockpicker/bootstrap-clockpicker.min.css">-->
    <link rel="stylesheet" href="css/flatpicker/flatpickr.min.css">

    <script type="text/javascript" src="js/jquery-3.2.1.js"></script>
    <!-- 引入 bootstrap 库 -->
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/bootstrapValidator.min.js"></script>
    <script type="text/javascript" src="js/flatpicker/flatpickr.min.js"></script>

    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=xZXH3sRzkIgsZa70oqf9uDzScnSb13Il"></script>

    <title>浏览任务</title>
    <link rel="stylesheet" href="css/global.css" />
    <link rel="stylesheet" href="css/taskBrowse.css" />
</head>


<body>


<div id="allmap"></div>

<div class="modal fade" id="taskPopup" >
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
                <div class="my-div-inline-left task-card-left">
                    <div>
                        <p id="task-card-reward">20</p>
                    </div>
                    <div>
                        <p id="task-card-requester"></p>
                    </div>
                </div>
                <div class="my-div-inline-right task-card-right">
                    <div>
                        <p id="task-card-desc"></p>
                    </div>
                    <button  class="btn btn-warning" id="open-task-detail">任务详情</button>
                </div>
                <div style="clear:both"></div>
            </div>

        </div>
    </div>
</div>

<div class="modal fade" id="detail" style="height:100%;overflow-y: scroll">
    <div class="modal-dialog"  >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×
                </button>
                <h4 class="modal-title" id="task-title">
                </h4>
            </div>
            <div class="modal-body">
                <table id="task-detail-table">
                    <tbody>
                    </tbody>
                </table>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">
                    返回
                </button>
                <button type="button" class="btn btn-primary " id="accept-task-button">
                    接受任务
                </button>
            </div>

        </div>
    </div>
</div>


<div class="modal fade" id="confirm-accept-modal">
    <div class="modal-dialog"  >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×
                </button>
                <h4 class="modal-title">
                    确认接收任务
                </h4>
            </div>
            <div class="modal-body">
                <span>确定在契约时间<span style="color: red" id="contract-time"></span>内完成该任务吗？</span>
                <p>（点击契约时间可进行修改，但不得晚于截止时间）</p>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    返回
                </button>
                <button type="button" class="btn btn-primary" id="confirm-accept-button">
                    确定
                </button>
            </div>

        </div>
    </div>
</div>


<div class="modal fade" id="change-contract-modal">
    <div class="modal-dialog"  >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×
                </button>
                <h4 class="modal-title">
                    选择契约时间
                </h4>
            </div>
            <div class="modal-body">
                <input class="flatpickr flatpickr-input form-control" data-enable-time="true"
                       data-enable-seconds="true" id="contract-clock" readonly="readonly" data-date-format="Y-m-d H:i:S" >
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="finish-contract-button">
                    完成
                </button>
            </div>

        </div>
    </div>
</div>


</body>


<script type="text/javascript">

    var map= new BMap.Map("allmap");
    //右上角,仅包含平移和缩放按钮
    var bottom_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM});
    map.addControl(bottom_right_navigation);

    var userId = <?php echo $userId?>;
    var userInfo = <?php var_dump($userInfo)?>;
    var currentLocation = -1;
    //获取的推荐任务列表
    var task_list, task_detail={};
    var currentTaskIndex = -1,currentTaskId = -1;
    var contract_time;

    var markerList = [];
    var unclickIcon = new BMap.Icon("img/location_icon_unselected.png", new BMap.Size(37,37), {anchor: new BMap.Size(18, 32)} );
    var clickIcon = new BMap.Icon("img/location_icon_selected.png", new BMap.Size(45,45), {anchor: new BMap.Size(22, 40)} );

    $(document).ready(function(){
        if(userId != -1){
            initTaskMap();
            $('#contract-clock').flatpickr();
        } else {
            alert("请先注册应用并绑定微信哦！" + userInfo);
        }
    });

    //点击任务详情按钮
    $('#open-task-detail').on('click', function(){
        $('#taskPopup').modal('hide');
        var action = "controller/getTaskInfo.php";
        var data = {
            "taskid": currentTaskId,
            "latitude": currentLocation.lat,
            "longitude": currentLocation.lng
        };
        $.ajax({
            type: "POST",
            url: action,
            data: {data:JSON.stringify(data)},
            success: function(response) {
                task_detail = JSON.parse(response.trim().replace(/\n/g,":"));
                $('#detail').modal('show');
                $('#detail').on('show.bs.modal', function () {
                    $('body,html').css('height','');
                });
                $('#detail').on('shown.bs.modal', function () {
                    $('body,html').css('height','');
                    var table = $('#task-detail-table tbody');
                    $('#task-title').html(task_detail['title']);
                    createTaskDetailPop(table);
                });
                $('#detail').on('hide.bs.modal', function () {
                    $('body,html').css('height','100%');
                });
            },
            error:function(request){
                alert("connection error");
            }
        });
    });

    //点击接受任务，弹出确认对话框
    $('#accept-task-button').on('click', function(){
        contract_time = task_detail.stages[task_detail.currentStage-1].contractTime;
        $('#detail').modal('hide');
        $('#confirm-accept-modal').modal('show');
    });

    //每次modal出现后都会调用，只写一遍
    $('#confirm-accept-modal').on('shown.bs.modal', function () {
        $('#contract-time').html(contract_time);
    });

    //确认在契约时间内接受任务
    $('#confirm-accept-button').on('click', function(){
        var action = "controller/simpleAcceptTask.php";
        var data = {
            "userid":userId,
            "taskid": task_detail.id,
            "currentstage": task_detail.currentStage,
            "starttime": new Date().Format("yyyy-MM-dd HH:mm:ss"),
            "contracttime": contract_time
        };
        $.ajax({
            type: "POST",
            url: action,
            data: {data:JSON.stringify(data)},
            success: function(response)
            {
                if(response == 1){
                    alert("成功接受任务！");
                    $('#confirm-accept-modal').modal('hide');
                    initTaskMap();
                } else {
                    alert("接受任务失败！");
                    $('#confirm-accept-modal').modal('hide');
                }
            },
            error:function(request){
                alert("connection error");
            }
        });
    });

    //自定义contracttime
    $('#finish-contract-button').on('click', function(){
        if(compareDate(task_detail.stages[task_detail.currentStage-1].ddl, $('#contract-clock').val())){
            contract_time = $('#contract-clock').val();
            $('#change-contract-modal').modal('hide');
            $('#confirm-accept-modal').modal('show');
        } else {
            alert("契约时间必须早于任务的截止时间：" + task_detail.stages[task_detail.currentStage-1].ddl);
        }
    });

    //判断修改的契约是否在ddl之前,d1:ddl d2:契约时间
    function compareDate(d1,d2) {
        return ((new Date(d1.replace(/-/g,"\/"))) >= (new Date(d2.replace(/-/g,"\/"))));
    }

    //点击契约时间进行修改
    $('#contract-time').on('click', function(){
        $('#confirm-accept-modal').modal('hide');
        $('#change-contract-modal').modal('show');
    });


    //初始化地图，获取当前浏览器位置
    function initTaskMap(){
        map.clearOverlays();
        //定位
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS) {
                if(currentLocation.lat != r.point.lat || currentLocation.lng != r.point.lng){
                    //标识用户当前位置
                    currentLocation = r.point;
                    map.centerAndZoom(currentLocation,17);
//                    map.centerAndZoom(new BMap.Point(121.606,31.1965),17);
                    var mk = new BMap.Marker(currentLocation, {icon:new BMap.Icon("img/my_location.png", new BMap.Size(37,37), {anchor: new BMap.Size(18, 32)} )});
                    map.addOverlay(mk);
//                    map.panTo(currentLocation);
                    getTaskList();
                }
            }else {
                alert('Get location failed: '+this.getStatus());
            }

        },{enableHighAccuracy: true});
    }

    function getTaskList(){
        var action = "controller/getRecommendedTask.php";
        var data = {
            "userid": userId,
            "latitude": currentLocation.lat,
            "longitude": currentLocation.lng
        };

        $.ajax({
            type: "POST",
            url: action,
            data: {data:JSON.stringify(data)},
            success: function(response)
            {
                task_list= JSON.parse(response);
                addTaskMarkers();
            },
            error:function(request){
                alert("连接出错，请稍后再试！");
            }
        });
    }

    function addTaskMarkers(){
        markerList = [];
        for (var i = 0; i < task_list.length; i ++) {
            (function(index){
                var task = task_list[index];
                //防止同一地点标记重合
                var lat = parseFloat(task.latitude) + (Math.random() - 0.5) * 0.0001;
                var lng = parseFloat(task.longitude) + (Math.random() - 0.5) * 0.0001;
                var point = new BMap.Point(lng, lat);
                var task_marker = new BMap.Marker(point, {icon:unclickIcon});
                task_marker.addEventListener("click",function() {
                    currentTaskIndex = index;
                    currentTaskId = task.id;
                    $('#task-card-reward').html(task.bonusReward);
                    $('#task-card-requester').html(task.requester);
                    $('#task-card-desc').html(task.stageDesc);
                    $('#taskPopup').modal('show');
                    $('#taskPopup').on('shown.bs.modal', function () {
                        // task card居中
                        $('#taskPopup .modal-dialog ').css('left',(screen.availWidth  - $('.modal-dialog ').width()-20)/2 + "px");
                    });
                });
                map.addOverlay(task_marker);
                markerList.push(task_marker);

            })(i);//调用时参数
        }

    }


    //填充任务详情弹出框内容
    function createTaskDetailPop(table){
        table.html('');
//        table.append("<tr style='font-weight: bold'> <td colspan='2' style='text-align: center'>" + task_detail['title'] +"</td> </tr>");
        table.append(createTableRow( "描述：", task_detail['description']));
        table.append(createTableRow("进度：", task_detail['progress']));
        table.append(createTableRow("奖励：", task_detail['bonusReward']));
        table.append(createTableRow("截止时间：", task_detail['deadline']));
        stages = task_detail['stages'];
        for(var i=0; i<stages.length; i++){
            var stage = stages[i];
//            alert(JSON.stringify(stage));
            table.append(createStageHeader(stage['name'],stage));
            table.append(createTableRow("描述：", stage['desc']));
            table.append(createTableRow("报酬：", stage['reward']));
            for(var j=0; j<stage['locations'].length; j++){
                if(stage['locations'][j] != null){
                    var location  = stage['locations'][j];
                    table.append(createLocationHeader(location['type']));
                    table.append(createTableRow( "地址：", location['address'].replace("=","\n")));
                    var inputs = stage['locations'][j]['inputs'];
                    if(null != inputs && inputs.length > 0){
                        table.append("<tr style='font-weight: bold'> <td colspan='2' >额外信息</td> </tr>");
                        for(var k=0; k<inputs.length; k++){
                            table.append(createTableRow(inputs[k]['desc']+":&nbsp&nbsp", inputs[k]['value']));
                        }
                    }
                    var outputs = stage['locations'][j]['outputs'];
                    if(null != outputs && outputs.length > 0){
                        table.append("<tr style='font-weight: bold'> <td colspan='2' >反馈</td> </tr>");
                        for(var k=0; k<outputs.length; k++){
                            var output = outputs[k];
                            if(output['type'] == 0){ //picture
                                table.append(createTableRow("图片：", output['desc']));
                            } else { //text/num/enum
                                switch (output['type']) {
                                    case 1:
                                        table.append(createTableRow("文本：", output['desc']));
                                        break;
                                    case 2:
                                        table.append(createTableRow("数字：", output['desc']));
                                        break;
                                    case 3:
                                        table.append(createTableRow("枚举：", output['desc']));
                                        break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    function createLocationHeader(type){
        var h="";
        if(type == 0){
            h = "<tr style='font-weight: bold'> <td colspan='2' style='text-align: center'>起点</td> </tr>";
        } else if(type == 1){
            h = "<tr style='font-weight: bold'> <td colspan='2' style='text-align: center'>终点</td> </tr>";
        }
        return h;
    }

    function createStageHeader(name, stage){
        var header;
        switch(stage['stageStatus']){
            case 0:
                header = " <tr style='color:#419DE4;font-weight: bold'> <td colspan='2' style='text-align: center'>"+ name + "&nbsp&nbsp&nbsp"+
                    "<img src='img/my_task_ongoing.png' style='width:20px;height:20px'></img></td> </tr>";
                if(stage['workerNames'] != null){
                    header +=  " <tr> <td class='td1'>接受者：</td> <td class='td2'>"+stage['workerNames'].join(",")+"</td> </tr>";
                }
                break;
            case 1:
                header = " <tr style='color:#419DE4;font-weight: bold'> <td colspan='2' style='text-align: center'>"+ name + "&nbsp&nbsp&nbsp"+
                    "<img src='img/task_finished.png' style='width:20px;height:20px'></img></td> </tr>";
                if(stage['workerNames'] != null){
                    header +=  " <tr> <td class='td1'>接受者：</td> <td class='td2'>"+stage['workerNames'].join()+"</td> </tr>";
                }
                break;
            case 2:
                if(null != stage['contractTime'] && ""!= stage['contractTime']){
                    header = " <tr style='color:#419DE4;font-weight: bold'> <td colspan='2' style='text-align: center'>"+ name + "&nbsp&nbsp&nbsp"+
                        "<img src='img/task_wanted.png' style='width:20px;height:20px'></img></td> </tr>";
                    header +=  " <tr> <td class='td1'>人数：</td> <td class='td2'>"+stage['workerNum']+"</td> </tr>";
                    header +=  " <tr style='color:red'> <td class='td1'>契约时间：</td> <td class='td2'>"+stage['contractTime']+"</td> </tr>";
                } else {
                    header = " <tr style='color:#419DE4;font-weight: bold'> <td colspan='2' style='text-align: center'>"+ name + "&nbsp&nbsp&nbsp"+
                        "<img src='img/task_waiting.png' style='width:20px;height:20px'></img></td> </tr>";
                    header +=  " <tr> <td class='td1'>人数：</td> <td class='td2'>"+stage['workerNum']+"</td> </tr>";
                    header +=  " <tr> <td class='td1'>截止时间：</td> <td class='td2'>"+stage['ddl']+"</td> </tr>";
                }
                break;
            case -1:
                header = " <tr style='color:#419DE4;font-weight: bold'> <td colspan='2' style='text-align: center'>"+ name + "&nbsp&nbsp&nbsp"+
                    "<img src='img/expired.png' style='width:20px;height:20px'></img></td> </tr>";
                break;
            default:alert("stageStatus error!");

        }
        return header;
    }

    function createTableRow(key, value){
        var row = " <tr> <td class='td1'>"+key+"</td> <td class='td2'>"+value+"</td> </tr>";
        return row;
    }

    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "H+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }


    //推荐任务列表
    //    task_list = [
    //        {
    //            "bonusReward": 56,
    //            "currentStage": 6,
    //            "deadline": 1490613945000,
    //            "stageDesc": "去丰巢取快递",
    //            "stageReward": 20,
    //            "id": 247,
    //            "latitude": 31.1965,
    //            "longitude":121.606,
    //            "progress": "6/2",
    //            "publishTime": 1490613945000,
    //            "templateId": 215,
    //            "taskTitle": "收快递",
    //            "userId": 247,
    //            "requester": "lab401",
    //            "stageContract": "2017/4/10 12:00:00"
    //        },
    //        {
    //            "bonusReward": 55,
    //            "currentStage": 6,
    //            "deadline": 1490613945000,
    //            "stageDesc": "去食堂买饭",
    //            "stageReward": 20,
    //            "id": 247,
    //            "latitude": 31.1977,
    //            "longitude":121.597,
    //            "progress": "6/2",
    //            "publishTime": 1490613945000,
    //            "templateId": 215,
    //            "taskTitle": "买饭",
    //            "userId": 247,
    //            "requester": "lab401",
    //            "stageContract": "2017/4/10 12:00:00"
    //        }
    //    ];

</script>





</html>




